<?php
/**
 * @link https://gitee.com/toshcn/yii2-oauth2-server
 * @copyright Copyright (c) 2018 len168.com
 * @license https://gitee.com/toshcn/yii2-oauth2-server/blob/master/LICENSE
 */

namespace toshcn\yii2\oauth2server;

class Server extends \OAuth2\Server
{
    use traits\ClassNamespace;

    /**
     * @var \toshcn\yii2\oauth2server\Module
     */
    protected $module;

    public function __construct(
        Module $module,
        $storage = array(),
        array $config = array(),
        array $grantTypes = array(),
        array $responseTypes = array(),
        \OAuth2\TokenType\TokenTypeInterface $tokenType = null,
        \OAuth2\ScopeInterface $scopeUtil = null,
        \OAuth2\ClientAssertionType\ClientAssertionTypeInterface $clientAssertionType = null
    ) {
        $this->module = $module;
        parent::__construct($storage, $config, $grantTypes, $responseTypes, $tokenType, $scopeUtil, $clientAssertionType);
    }

    public function createAccessToken($clientId, $userId, $scope = null, $includeRefreshToken = true)
    {
        $accessToken = $this->getAccessTokenResponseType();
        return $accessToken->createAccessToken($clientId, $userId, $scope, $includeRefreshToken);
    }

    public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null)
    {
        if(!($request instanceof \OAuth2\RequestInterface)) {
            $this->module->set('request', Request::createFromGlobals());
            $request = $this->module->getRequest();
        }
        parent::verifyResourceRequest($request, $response, $scope);
    }

    public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null)
    {
        if(!($request instanceof \OAuth2\RequestInterface)) {
            $this->module->set('request', Request::createFromGlobals());
            $request = $this->module->getRequest();
        }
        return parent::handleTokenRequest($request, $response);
    }


    public function handleAuthorizeRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $is_authorized = true, $user_id = null)
    {
        if(!($request instanceof \OAuth2\RequestInterface)) {
            $this->module->set('request', Request::createFromGlobals());
            $request = $this->module->getRequest();
        }
        $response = is_null($response) ? new Response() : $response;

        return parent::handleAuthorizeRequest($request, $response, $is_authorized, $user_id);
    }
}
